const { Client } = require('ssh2');
const serverManager = require('./serverManager');
const {encrypt} = require("./crypto");
const {decrypt} = require("./crypto");
// 日志工具（中国标准时间UTC+8）
const logger = (message) => {
    const now = new Date();
    const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const chinaTimeStr = chinaTime.toISOString().replace('Z', '+08:00');
    console.log(`[${chinaTimeStr}] ${message}`);
};
async function changePassword(username, newPassword, accountName, targetHost) {

    // 从数据库获取服务器配置
    const serverConfig = await serverManager.getServerInfo(accountName, targetHost);
    if (!serverConfig) {
        logger(`未找到服务器配置信息: ${accountName}, ${targetHost}`);
        logger('[ERROR]:未找到服务器配置信息');
        return reject(new Error('未找到服务器配置信息'));
    } else if (serverConfig.success === 'false')
    {
        logger(`[ERROR]:未找到服务器配置信息`);
        return reject(new Error(`未找到服务器配置信息,${serverConfig.error}.`));
    }

    return new Promise((resolve, reject) => {
        logger(`开始执行修改密码: ${accountName}, ${targetHost}`);
        const conn = new Client();

        const rootpasswd = decrypt(serverConfig.rootPassword);

        // logger(`debug---------------------------------------------: ${rootpasswd}, ${targetHost}, ${serverConfig.port}`);

        // 处理连接错误
        conn.on('error', (err) => {
            logger(`[ERROR]:SSH连接错误: ${err.message}`);
            reject(new Error(`[ERROR]:SSH连接失败: ${err.message}`));
        });

        conn.on('ready', () => {
            logger(`SSH连接成功，准备执行密码修改命令`);
            // 使用root用户执行chpasswd命令
            logger(`准备修改用户 ${accountName} 的密码`)
            // 对输入进行转义处理，防止命令注入
            const escapedAccountName = accountName.replace(/[&|;$<>\'"`()]/g, '');
            const escapedNewPassword = newPassword.replace(/[&|;$<>\'"`()]/g, '');
            
            conn.exec(`echo "${escapedAccountName}:${escapedNewPassword}" >> /root/pwd.txt;chmod 600 /root/pwd.txt;echo "${escapedAccountName}:${escapedNewPassword}" | chpasswd`, (err, stream) => {
                if (err) {
                    logger(`[ERROR]:执行命令出错: ${err.message}`);
                    conn.end();
                    return reject(new Error(`[ERROR]:执行命令失败: ${err.message}`));
                }

                let stdout = '';
                let stderr = '';

                stream.on('data', (data) => {
                    stdout += data;
                });

                stream.stderr.on('data', (data) => {
                    stderr += data;
                });

                stream.on('close', (code) => {
                conn.end();
                if (code !== 0) {
                    logger(`[ERROR]:命令执行失败，退出码: ${code}, 错误: ${stderr}`);
                    reject(new Error(`[ERROR]:修改密码失败: ${stderr || '未知错误'}`));
                } else {
                    logger(`命令执行成功，退出码: ${code}, 输出: ${stdout}`);
                    logger(`修改密码完成: ${accountName}`);
                    resolve({ success: true, message: '密码修改成功' });
                }
            });
            });
        });

        // 连接到服务器，使用root用户
        conn.connect({
            host: serverConfig.host,
            port: serverConfig.port,
            username: 'root', // 使用root用户登录
            password: rootpasswd
        });
    })
}

module.exports = { changePassword };